{% extends 'app_admin/admin_base.html' %}
{% load static %}
{% load i18n %}
{% block title %}用户管理{% endblock %}
{% block content %}
<div class="layui-card">
    <div class="layui-card-body">
        <div class="layui-card-header" style="margin-bottom: 10px;">
        <div class="layui-row">
            <span style="font-size:18px;">用户管理
            </span>
        </div>
        </div>
        <div class="layui-row">
            <div class="layui-form-item">
                <div class="layui-input-inline">
                    <input type="text" name="username" id="username" required lay-verify="required" placeholder="输入用户名" autocomplete="off" class="layui-input">
                </div>
                <button class="pear-btn pear-btn-sm" id="search"><i class="layui-icon layui-icon-search"></i>搜索</button>
                <button class="pear-btn pear-btn-primary pear-btn-sm" onclick="createUser()" type="button"><i class="layui-icon layui-icon-addition"></i>新增用户</button>
                <button class="pear-btn pear-btn-primary pear-btn-sm" onclick="createSuperUser()" type="button"><i class="layui-icon layui-icon-addition"></i>添加管理员</button>
            </div>
        </div>
        <div class="layui-row">
            <table class="layui-table"  id="user-list" lay-filter="user-table"></table>
        </div>
    </div>
</div>
{% endblock %}

{% block custom_script %}
    <!-- 用户角色模板 -->
    <script type="text/html" id="userRole">
      {% verbatim %}
          {{#  if(d['is_superuser']){ }}
                超级管理员
          {{#  } else { }}
            普通用户
          {{#  } }}
      {% endverbatim %}
    </script>
    <!-- 用户状态模板 -->
    <script type="text/html" id="userStatus">
      {% verbatim %}
          {{#  if(d['is_active']){ }}
              <i class="layui-icon layui-icon-ok-circle" style="color: green"/>
          {{#  } else { }}
              <i class="layui-icon layui-icon-close-fill" style="color: red"/>
          {{#  } }}
      {% endverbatim %}
    </script>
    <!-- 注册时间 -->
    <script type="text/html" id="registerTime">
        {% verbatim %}
        {{layui.util.toDateString(d.date_joined,  "yyyy-MM-dd HH:mm:ss")}}
        {% endverbatim %}
    </script>
    <!-- 最后登录时间 -->
    <script type="text/html" id="lastLoginTime">
        {% verbatim %}
        {{layui.util.toDateString(d.last_login,  "yyyy-MM-dd HH:mm:ss")}}
        {% endverbatim %}
    </script>
    <!-- 用户操作模板 -->
    <script type="text/html" id="userOpera">
      {% verbatim %}
      <a class="layui-table-link" href="javascript:void(0);" onclick="changeInfo('{{ d.id }}','{{ d.username }}')">编辑</a>&nbsp;&nbsp;
      <!-- <a class="layui-table-link" href="javascript:void(0);" onclick="changePwd('{{ d.id }}','{{ d.username }}')">修改密码</a>&nbsp;&nbsp; -->
      <a class="layui-table-link" href="javascript:void(0);" onclick="delUser('{{ d.id }}','{{ d.username }}')">删除</a>
      {% endverbatim %}
    </script>
<script>
    layui.use(['table','jquery','form','layer','element','table'], function() {
        let table = layui.table;
        let form = layui.form;
        let $ = layui.jquery;
        let layer = layui.layer;
        let element = layui.element;
        $.ajaxSetup({
            data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
            headers: {"X-CSRFToken":'{{ csrf_token }}'},
        });
        //获取用户列表，执行表格渲染
        table.render({
            elem: '#user-list',
            url: "{% url 'api_admin_users' %}",
            method:'get',
            where:{
                'username':$("#username").val(),
            },
            page:true,
            cols: [[
                {field:'username',title:'用户名',width:160},
                {field:'first_name',title:'昵称',width:160},
                {field:'email',title:'电子邮箱',width:160},
                {field:'is_superuser',title:'用户角色',width:100,templet:'#userRole'},
                {field:'date_joined',title:'注册时间',width:160,templet:'#registerTime'},
                {field:'last_login',title:'最后登录时间',width:160,templet:'#lastLoginTime'},
                {field:'is_active',title:'状态',width:60,templet:'#userStatus'},
                {field:'oprate',title:'操作',width:180,templet:'#userOpera'},
            ]],
            skin: 'line',
        });
        //新建用户
        createUser = function(){
            layer.open({
                type:1,
                title:'新建用户',
                area:'300px;',
                id:'createUser',//配置ID
                content:'<div style="padding: 20px;"><input class="layui-input" type="text" id="user" style="margin-bottom:10px;" placeholder="输入用户名，长度不少于5位" required  lay-verify="required"><input class="layui-input" type="email" id="email" style="margin-bottom:10px;" placeholder="输入电子邮箱" required  lay-verify="required"><input class="layui-input" type="password" id="password" placeholder="输入密码，长度不少于6位" required  lay-verify="required"></div>',
                btn:['确定','取消'], //添加按钮
                btnAlign:'c', //按钮居中
                yes:function (index,layero) {
                    layer.load(1);
                    data = {
                        'username':$("#user").val(),
                        'password':$("#password").val(),
                        'email':$("#email").val()
                    }
                    $.ajax({
                        url:"{% url 'api_admin_users' %}",
                        method:'post',
                        data:data,
                        success:function(r){
                            layer.closeAll('loading');
                            if(r.code === 0){
                                //创建成功，刷新页面
                                layer.closeAll();
                                table.reload('user-list');
                            }else{
                                //创建失败，提示
                                // console.log(r)
                                layer.msg(r.data)
                            }
                        },
                        error:function(){
                            layer.closeAll('loading');
                            layer.msg("请检查输入信息是否正确")
                        }
                    })
                },
            })
        };
        createSuperUser = function(){
            layer.open({
                type:1,
                title:'新增管理员',
                area:'300px;',
                id:'createSuperUser',//配置ID
                content:'<div style="padding: 20px;"><input class="layui-input" type="text" id="user2" style="margin-bottom:10px;" placeholder="输入用户名，长度不少于5位" required  lay-verify="required"><input class="layui-input" type="email" id="email2" style="margin-bottom:10px;" placeholder="输入电子邮箱" required  lay-verify="required"><input class="layui-input" type="password" id="password2" placeholder="输入密码，长度不少于6位" required  lay-verify="required"></div>',
                btn:['确定','取消'], //添加按钮
                btnAlign:'c', //按钮居中
                yes:function (index,layero) {
                    layer.load(1);
                    data = {
                        'username':$("#user2").val(),
                        'password':$("#password2").val(),
                        'email':$("#email2").val(),
                        'user_type':1,
                    }
                    $.ajax({
                        url:"{% url 'api_admin_users' %}",
                        method:'post',
                        data:data,
                        success:function(r){
                            layer.closeAll('loading');
                            if(r.code === 0){
                                //创建成功，刷新页面
                                layer.closeAll();
                                table.reload('user-list');
                            }else{
                                //创建失败，提示
                                // console.log(r)
                                layer.msg(r.data)
                            }
                        },
                        error:function(){
                            layer.closeAll('loading');
                            layer.msg("请检查输入信息是否正确")
                        }
                    })
                },
            })
        };
        //修改用户密码
        changePwd = function(uid,username){
            layer.open({
                type:1,
                title:'修改密码',
                area:'300px;',
                id:'changePwd',
                content:'<div style="padding:10px 0 0 20px;">修改用户[' + username + ']的密码：</div><div style="padding: 20px;"><input class="layui-input" type="password" id="newPwd1" style="margin-bottom:10px;" placeholder="输入新密码" required  lay-verify="required"><input class="layui-input" type="password" id="newPwd2" placeholder="再次确认新密码" required  lay-verify="required"></div>',
                btn:['确认修改','取消'],
                yes:function (index,layero) {
                    layer.load();
                    data = {
                        'obj':'pwd',
                        'password':$("#newPwd1").val(),
                        'password2':$("#newPwd2").val(),
                    }
                    $.ajax({
                        url:'/admin/api/user/'+uid,
                        type:'put',
                        data:data,
                        success:function(r){
                            layer.closeAll();
                            if(r.code === 0){
                                //删除成功
                                layer.msg(r.data)
                                // table.reload('user-list',{page:{curr:1}});
                            }else{
                                //删除失败，提示
                                //console.log(r)
                                layer.msg(r.data)
                            }
                        },
                        error:function(){
                            layer.closeAll();
                            layer.msg(r.data)
                        }
                    });
                },
            })
        };
        // 修改用户资料
        changeInfo = function(uid,username){
            location.href = "{% url 'user_profile' %}?id="+uid
        };
        //删除用户
        delUser = function(uid,username){
            layer.open({
                type:1,
                title:'删除用户',
                area:'300px;',
                id:'delPro',//配置ID
                content:'<div style="margin-left:10px;">警告：此操作将删除用户'+username+'及其文集文档！协作文档将转移给文集所有者</div>',
                btn:['确定','取消'], //添加按钮
                btnAlign:'c', //按钮居中
                yes:function (index,layero) {
                    layer.load(1);
                    $.ajax({
                        url:'/admin/api/user/'+uid,
                        type:'delete',
                        success:function(r){
                            layer.closeAll();
                            if(r.code === 0){
                                //删除成功
                                table.reload('user-list',{page:{curr:1}});
                            }else{
                                //删除失败，提示
                                //console.log(r)
                                layer.msg(r.data)
                            }
                        },
                        error:function(){
                            layer.closeAll();
                            layer.msg(r.data)
                        }
                    });
                },
            });
        };
        // 监听搜索按钮
        $("#search").click(function(){
            table.reload('user-list',{
                where:{
                    'username':$("input[name=username]").val(),
                },
            })
        });
    })
</script>
{% endblock %}